# Author ： chosen-yn
import random
import time
from celery import shared_task
from django.conf import settings
from django.core.mail import send_mail
from celery import Task
from utils.common_logger import logger


# 成功失败邮件告警
class SendEmailTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        info = f'任务成功！任务id是：{task_id},参数是:{args}'
        send_mail('celery任务监控成功告警', info, settings.EMAIL_HOST_USER, ['1115826327@qq.com'])
        logger.info(info)
        print('------ 成功 ------')

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        info = f'任务失败，任务id是：{task_id},参数是:{args}，失败信息是：{exc}'
        send_mail('celery任务监控..失败..告警', info, settings.EMAIL_HOST_USER, ['1115826327@qq.com'])
        logger.info(info)
        print('------ 失败 ------')

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        print(f'任务id为：:{task_id} , 参数为:{args} , 重试了 !  错误信息为: {exc}')


@shared_task(base=SendEmailTask, bind=True)
def add(self, a, b):
    time.sleep(3)
    return a + b


@shared_task
def send_email(mail='1115826327@qq.com'):
    print('模拟发送延迟--开始')
    time.sleep(3)
    print('模拟发送延迟--结束')
    return '邮件发送成功：%s' % mail


from .models import Banner
from .serializer import BannerSerializer
from django.core.cache import cache
from django.conf import settings


@shared_task
def update_banner():
    # 1 去 banner表中查出所有数据
    banner_list = Banner.objects.all().filter(is_show=True, is_delete=False).order_by('orders')
    # 2 对它序列化
    serializer = BannerSerializer(instance=banner_list, many=True)
    # 2.1 每个图片前要拼接地址
    for item in serializer.data:
        item['image'] = settings.BACKEND_URL + item['image']
    # 3 放到缓存中
    cache.set('cache_banner_list', serializer.data)
    return True


########### 异步秒杀 ###########
@shared_task
def seckill(course_id):
    print('根据课程id：%s，查询课程是否还有剩余，耗时1s' % course_id)
    time.sleep(1)
    res = random.choice([True, False])
    if res:  # 模拟如果有库存
        print('扣减库存，耗时1s')
        time.sleep(1)
        print('下单，生成订单，耗时1s')
        time.sleep(1)
        return True
    else:
        return False

